#!/usr/bin/env python
# encoding: utf-8
'''
@author: zhaowenpeng
@contact: winston@peipeiyun.com
@software: garner
@file: auth.py
@time: 2020/6/2 3:43 下午
@desc:
'''


from functools import wraps
import logging
import traceback
from sanic.response import json
from sanic.request import json_loads
from core.utils import get_auth_cookies

def check_authorization(request):
    '''校验cookie'''
    flag = False
    try:
        token = request.headers.get('token', '').strip()
        if token:
            AUTH_TOKEN = request.app.config['AUTH_TOKEN']
            cookies = get_auth_cookies(AUTH_TOKEN,token)
            flag=True
            print(cookies)
        print(token)
    except:
        logging.error(traceback.format_exc())
        flag = False
    return flag

def authorized():
    def decorator(f):
        @wraps(f)
        async def decorated_function(request, *args, **kwargs):
            is_authorized = check_authorization(request)
            if request.path.startswith('/v1/login'):
                resp = await f(request, *args, **kwargs)
                return resp
            else:
                if is_authorized:
                    resp = await f(request, *args, **kwargs)
                    return resp
                else:
                    return json({'code':203,'info':''})
        return decorated_function
    return decorator


